package cn.mystyle.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.mystyle.common.enums.CommonResultCode;
import cn.mystyle.common.exception.MyRuntimeException;
import cn.mystyle.model.user.UserInfo;

/**
 * @author clark
 * 用户处理类
 */
public class UserUtil
{
    /**
     * 登录
     * @param request HTTP请求
     * @param user 登录用户
     */
    public static void seesionLogin(HttpServletRequest request, UserInfo user)
    {
        HttpSession httpSession = request.getSession(true);
        
        httpSession.setAttribute(Constant.SESSION_USER_KEY, user);
    }
    
    /**
     * 获取会话用户，如果用户未登录则会抛出异常
     * @param request HTTP请求
     */
    public static UserInfo seesionUser(HttpServletRequest request)
    {
        HttpSession httpSession = request.getSession();
        if (null != httpSession && null != httpSession.getAttribute(Constant.SESSION_USER_KEY))
        {
            return (UserInfo)httpSession.getAttribute(Constant.SESSION_USER_KEY);
        }
        
        // 抛出请登录运行异常
        throw new MyRuntimeException(CommonResultCode.SERVICE_BUSINESS_6011000.getCode(),
            CommonResultCode.SERVICE_BUSINESS_6011000.getMsg());
    }
    
    /**
     * 获取会话用户，不抛异常
     * @param request HTTP请求
     */
    public static UserInfo seesionUserNoThrow(HttpServletRequest request)
    {
        HttpSession httpSession = request.getSession();
        if (null != httpSession && null != httpSession.getAttribute(Constant.SESSION_USER_KEY))
        {
            return (UserInfo)httpSession.getAttribute(Constant.SESSION_USER_KEY);
        }
        return null;
    }
    
    /**
     * 注销
     * @param request HTTP请求
     */
    public static void seesionLoginOut(HttpServletRequest request)
    {
        HttpSession httpSession = request.getSession();
        if (null != httpSession)
        {
            httpSession.removeAttribute(Constant.SESSION_USER_KEY);
        }
    }
}
